import { Route, Redirect } from 'react-router-dom';
import cookie from '../../utils/cookies';
import { LoginPage, Error404 } from '../Before/routerConfig';

const RouteWithSubRoutes = (route) => {
	return (
		<Route
			path={route.path}
			render={props => {
				document.title = route.title
				return <route.component {...props}></route.component>
			}}
		/>
	);
}

const FrontendAuth = (props) => {
	const { location, config } = props
	let { pathname } = location

	const target = config.find(e => e.path === pathname)
	if(!target){
		return <Redirect to={{pathname: Error404.path}} />
	}
	if((target.auth && cookie.getCookie('user-status') === 'login') || !target.auth){
		return <RouteWithSubRoutes {...target} />
	}else{
		return <Redirect to={{pathname: LoginPage.path}} />
	}
}

export default FrontendAuth;